<template>
  <div class="echarts" ref="echartsPie" :style="{ minHeight: '100px' }"></div>
</template>
<script>
import { onResizeChang } from "../js/common";
export default {
  name: "pie",
  props: {
    // 类型
    type: {
      type: String,
    },
    // 一些配置项
    setting: {
      type: Object,
      default: {},
    },
    // 数据
    data: {
      type: [Object, Array],
      default: [],
    },
  },
  data() {
    return {};
  },
  created() {
    // 监听屏幕改变的话就调用
    onResizeChang("start", this.onResizeChange);
  },
  methods: {
    echartInit() {
      var myChart = this.$echarts.init(this.$refs.echartsPie);
      var option = {
        series: [
          {
            color: ["#009DFF", "#20E4FF"],
            name: "",
            type: "pie",
            radius: this.radius,
            label: {
              normal: {
                show: true,
                position: "center",
                formatter: () => {
                  return `${this.rate} \n\n${this.centerTitle}`;
                },
                textStyle: {
                  fontSize: 16,
                  color: "#ffffff",
                },
              },
            },
            data: this.data || [],
          },
        ],
      };
      myChart.setOption(option);
    },
    // 重新计算
    onResizeChange() {
      var myChart = this.$echarts.init(this.$refs.echartsPie);
      myChart.resize();
    },
  },
  mounted() {
    this.echartInit();
  },
  computed: {
    // 环比重
    radius() {
      return this.setting.radius || "80%";
    },
    // 比率
    rate() {
      let rate = this.setting.number;
      let res;
      if (typeof rate === "number") {
        res = `${rate * 100} %`;
      } else if (typeof rate == "string" && rate.includes("%")) {
        res = rate;
      } else {
        res = "";
      }
      return res;
    },
    // 文字
    centerTitle() {
      return this.setting.title || "";
    },
  },
  // 销毁
  beforeDestroy() {
    onResizeChang("end", this.onResizeChange);
  },
};
</script>
<style lang="less" scoped>
.echarts {
  width: 100%;
  height: 100%;
}
</style>
